package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommentResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.LoadBalancer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/consumer/payment")
@Slf4j
public class OrderController {
    public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancer balancer;
    @Resource
    private DiscoveryClient discoveryClient;
    @PostMapping("/create")
    public CommentResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/cretePayment",payment,CommentResult.class);
    }
    @GetMapping("/getPaymentById")
    public CommentResult<Payment> getPaymentById(@RequestParam Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/getPaymentById/"+id,CommentResult.class);
    }
    @GetMapping("/getProviderInfo")
    public CommentResult getProviderInfo(){
        return restTemplate.getForObject(PAYMENT_URL+"/getProviderInfo",CommentResult.class);
    }
    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB()
    {
//        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
//
//        if(instances == null || instances.size()<=0) {
//            return null;
//        }
//        ServiceInstance serviceInstance = balancer.instances(instances);
//        URI uri = serviceInstance.getUri();
//        System.out.println(uri);
        return restTemplate.getForObject(PAYMENT_URL+"/payment/lb",String.class);
    }
}
